<?php

namespace App\Http\Controllers\Admin;
use App\DTOS\Admin\UserRoleDTO;
use App\DTOS\Admin\UserMemberDTO;
use App\Http\Controllers\Controller;
use App\Models\Game\RoleMail;
use App\Services\Game\UserMemberService;
use App\Services\Game\UserRoleService;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Http\Request;

class RoleMailController extends Controller
{
    private Request $request;
    private UserRoleService $userRoleService;
    private UserMemberService $userMemberService;

    public function __construct(Request $request,UserRoleService $userRoleService,UserMemberService $userMemberService)
    {
        $this->request = $request;
        $this->userRoleService = $userRoleService;
        $this->userMemberService = $userMemberService;
    }

    public function buildData()
    {
        MyLog::info('邮件查询');
        global $gameArea;
        $searchData = $this->request->all();
        $memid = data_get($searchData,'memid');
        $roleName = data_get($searchData,'roleName');
        $roleIds = data_get($searchData,'roleIds');
        $gameArea = data_get($searchData,'gameArea');

        $roleId = data_get($searchData,'roleId');
        $limit= data_get($searchData,'limit');
        $page = data_get($searchData,'page');
        $createDateTimeBegin = data_get($searchData,'createDateBegin');
        $createDateTimeEnd = data_get($searchData,'createDateEnd');
        $roleMail = RoleMail::query();

        if ($createDateTimeBegin){
            $roleMail->where("receiveTime",">=",strtotime($createDateTimeBegin));
        }
        if ($createDateTimeEnd){
            $roleMail->where("receiveTime","<=",strtotime($createDateTimeEnd));
        }
        if ($roleId) {
            $roleMail->where('roleId',$roleId);
        }
        if ($memid) {
            $roleMail->where('memid',$memid);
        }

        $res= $roleMail->orderByDesc('id')->paginate($limit,'*','page',$page);
        $res1 = [];
        $data = $res->items();
        foreach($data as &$datum){
            $datum['gameArea'] = $gameArea;
            $datum['logDate'] = date("Y-m-d H:i:s",$datum['receiveTime']);

        }
        $res1['data'] = $data;
        $res1['count'] = $res->total();
        $res1['code'] = 0;
        return $res1;
    }

    public function paginate(){
        try {
            MyLog::info('邮件查询');
            $res = $this->buildData();
            return ResponseUtil::json($res);
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function export(){
        try {
            $res = $this->buildData();
            $excelRows = [
                ['记录时间','服务器ID','账号','角色ID','角色名','货币类型','变化前','变动数','变化后','起点','结点','得失','操作类型']
            ];
            foreach($res['data'] as $datum){
                $excelRows[] = [
                    $datum['logTime'] ?? null,
                    $datum['serverId'] ?? null,
                    "'".$datum['memberName'] ?? null,
                    "'".$datum['roleId'] ?? null,
                    $datum['nick'] ?? null,
                    $datum['moneyTypeName'] ?? null,
                    $datum['amountBefore'] ?? null,
                    $datum['amountChanged'] ?? null,
                    $datum['amountAfter'] ?? null,
                    $datum['source'] ?? null,
                    $datum['target'] ?? null,
                    $datum['getOrLost'] ?? null,
                    $datum['opTypeName'] ?? null,
                ];
            }
            return ResponseUtil::success(cacheDownload(arrayToScvContent($excelRows),'.货币日志.csv'));
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }


    public function exportAll(){
        try {
            $res = $this->buildDatas();
            $excelRows = [
                ['记录时间','服务器ID','账号','角色ID','角色名','货币类型','变化前','变动数','变化后','起点','结点','得失','操作类型']
            ];
            foreach($res['data'] as $datum){
                $excelRows[] = [
                    $datum['logTime'] ?? null,
                    $datum['serverId'] ?? null,
                    "'".$datum['memberName'] ?? null,
                    "'".$datum['roleId'] ?? null,
                    $datum['nick'] ?? null,
                    $datum['moneyTypeName'] ?? null,
                    $datum['amountBefore'] ?? null,
                    $datum['amountChanged'] ?? null,
                    $datum['amountAfter'] ?? null,
                    $datum['source'] ?? null,
                    $datum['target'] ?? null,
                    $datum['getOrLost'] ?? null,
                    $datum['opTypeName'] ?? null,
                ];
            }
            return ResponseUtil::success(cacheDownload(arrayToScvContent($excelRows),'.货币日志.csv'));
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    //全服数据组装
    public function buildDatas()
    {
        global $gameArea;
        $searchData = $this->request->all();
        $username = data_get($searchData,'username');
        $roleName = data_get($searchData,'roleName');
        $opTypes = data_get($searchData,'opTypes');

        if ($opTypes) {
            $opTypes = explode(',',$opTypes);
            foreach($opTypes as &$opType){
                $opType = (int)$opType;
            }
            $searchData['opTypes'] = $opTypes;
        }
        $gameRoleTDO = new UserRoleDTO(['limit'=>9999999]);
        $searchedRoleTable = false;
        if ($username){
            $searchedRoleTable = true;//间接搜索了角色表
            $gameRoleTDO->setUsername($username);
        }
        if ($roleName){
            $searchedRoleTable = true;
            $gameRoleTDO->setNick($roleName);
        }
        if ($searchedRoleTable){ //最后搜索角色表
            $gameRoleTDO->setFields(['id']);
            $paginate = $this->userRoleService->paginate($gameRoleTDO);
            $roles = $paginate->items();
            $roleIds = collect($roles)->pluck('id')->toArray();
            if (empty($roleIds)){
                throw new \Exception("没有数据");
            }
            $searchData['roleIds'] = $roleIds;
        }

        $res = callRpc("/MoneyChangeService/paginate",$searchData,['gameArea'=>0]); //查询的ES
        MyLog::info('返回数据长度:'.json_encode(count($res)));
        return $res;
    }

}
